import type { EnumGender } from "@/api/siderBar/model"
import { postMyEdituserinfo } from "@/api/siderBar/my"
import { useUserStore } from "@/stores"
import { message } from "ant-design-vue"

type FormState = {
    gender?: EnumGender
}
export function useEditGender(fn?: IFn) {
    const userStore = useUserStore()
    const { state: showGender, on: openGender, off: closeGender } = useSwitch(false)
    const {
        clearValidate,
        formLoading,
        formRef,
        formState,
        rules,
        handleFormSubmit,
        resetFormState
    } = useFormState<FormState>({
        getInitialState() {
            return {}
        },
        rules: {
            gender: {
                required: true
            }
        }
    })
    useEffectScope(() => {
        watch(showGender, () => {
            if (showGender.value === false) {
                clearValidate()
                resetFormState()
            }
        })
    })
    function triggerGender(gender?: EnumGender) {
        if (isSetValue(gender)) {
            formState.value.gender = gender
        }
        openGender()
    }
    async function handleSubmit() {
        await handleFormSubmit(values => {
            return postMyEdituserinfo({
                gender: values.gender!,
                name: userStore.userInfo?.name!,
                avatar: userStore.userInfo?.avatar,
                jobId: userStore.userInfo?.jobId,
                position: userStore.userInfo?.position,
                weChat: userStore.userInfo?.weChat
            })            
        })
        closeGender()
        message.success("修改成功")
        fn?.()
    }
    return {
        formLoading,
        formState,
        rules,
        showGender,
        triggerGender,
        handleSubmit,
        formRef,
        genderOptions
    }
}